import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    companyid: '',
    avatar: '',
    roles: [],
    permissions: [],
    selectcompanyid: '',
    user: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_COMPANYID: (state, companyid) => {
      state.companyid = companyid
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_SELECTCOMPANYID: (state, selectcompanyid) => {
      state.selectcompanyid = selectcompanyid;
      window.localStorage.setItem("selectcompanyid", selectcompanyid);
    },
    SET_USER: (state, user) => {
      state.user = user;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      cleartreeDeptuserCache();
      const logintype = "pc"
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid

      return new Promise((resolve, reject) => {
        login(logintype, username, password, code, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    UserValid({ commit }, res) {
      return new Promise((resolve, reject) => {
        cleartreeDeptuserCache();
        setToken(res.token)
        commit('SET_TOKEN', res.token)
        resolve()
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        var res = {
          "msg": "操作成功",
          "code": 200,
          "permissions": [
            "org:lr:list",
            "safetymanage:category:remove",
            "workticket:confined:query",
            "train:course:remove",
          ],
          "roles": [
            "ZYSQFCSH",
            "ZYSQGSSH",
            "JSAFXYP",
            "YHPAMKYH",
            "GSJGLY",
            "JSASP"
          ],
          "user": {
            "id": 62058,
            "userName": "adminxjyh",
            "password": "$2a$10$AxLvhDMf5BNUN7LBZKd3hud5u8baQworzl0VNcvNxx7XVqjmqJnsa",
            "memo": null,
            "valid": true,
            "type": null,
            "departmentId": 7424,
            "departmentcode": "1001",
            "departmentname": "ai有限公司",
            "validMessage": null,
            "profilePhoto": null,
            "email": null,
            "userFullName": "管理员",
            "code": null,
            "workCode": null,
            "phone": null,
            "stationid": null,
            "stationname": null,
            "loginIp": "223.104.122.101",
            "loginDate": "2024-11-20 14:18:04",
            "unionid": null,
            "issys": 1,
            "token": "login_tokens:e0e9f364-3f75-4d85-884a-9ee6cf9f8c08",
            "companyId": 30,
            "companyName": null,
            "safepromiseid": null,
            "mobileMe": "866746735335091",
            "company": {
              "id": 30,
              "name": "ai有限公司",
              "code": "YH",
              "linkMan": null,
              "phone": null,
              "status": null,
              "memo": null,
              "valid": null,
              "longitude": "89.2445687406739",
              "latitude": "44.89323419018862",
              "shortname": "ai有限公司",
              "safetytime": null,
              "validday": null,
              "validtime": null,
              "userName": null,
              "userFullName": null,
              "password": null,
              "roleids": null,
              "currentuser": null
            },
            "params": {},
            "leveltype": null,
            "ispass": null,
            "roleIds": null,
            "postIds": null,
            "menuId": null,
            "roleId": null,
            "ids": null,
            "departmentIds": null,
            "listtu": null,
            "ccount": null,
            "submitStartDate": null,
            "submitEndDate": null,
            "usage": null,
            "admin": false
          }
        };
        var user=res.user;
        const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', res.roles)
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT'])
        }
        if (res.permissions && res.permissions.length > 0) {
          commit('SET_PERMISSIONS', res.permissions)
        } else {
          commit('SET_PERMISSIONS', ['PERMISSION_DEFAULT'])
        }
        commit('SET_COMPANYID', user.companyId)
        commit('SET_NAME', user.userName)
        commit('SET_AVATAR', avatar)
        commit('SET_USER', res.user);
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      cleartreeDeptuserCache();
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      cleartreeDeptuserCache();
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    //选择组织机构
    selectcompanyid({ commit }, data) {
      commit('SET_SELECTCOMPANYID', data.selectcompanyid)
    },
  }
}

//清除部门用户缓存数据
function cleartreeDeptuserCache() {
  window.localStorage.setItem("treeDeptuser", "");
  window.localStorage.setItem("deptusertime", "");
}

export default user
